﻿using System;
using UnityEngine;
using Zenject;
using System.Linq;
using System.Collections;

namespace DiIoc.DemoGame
{
    public class MoleManager : IInitializable, ITickable
    {
        readonly Mole.Pool _molePool;
        readonly SignalBus _signalBus;
        /// <summary>
        /// mole产生间隔
        /// TODO: 在game settings中设置初始间隔大小
        /// </summary>
        float _moleInstantiateInterval = 1;
        /// <summary>
        /// 计算下次周期的临时变量
        /// </summary>
        float nextTime = 2;
        /// <summary>
        /// Mole产生地点二维数组
        /// </summary>
        MolePositionState[] molePositionStates; 
        /// <summary>
        /// 不继承MonoBehaviour,我们可以用构造函数注入
        /// </summary>
        /// <param name="moleFactory"></param>
        public MoleManager(Mole.Pool molePool,SignalBus signalBus)
        {
            _molePool = molePool;
            _signalBus = signalBus;
            _signalBus.Subscribe<MoleSignal>(OnMoleSignalArriving);
        }
        /// <summary>
        /// 接受Mole Signal
        /// </summary>
        private void OnMoleSignalArriving(MoleSignal signal)
        {
            RemoveMole(signal.Mole);
        }

        public void Initialize()
        {
            SetInitMolePositionStates(); 
        }
        
        /// <summary>
        /// 不断的spawn
        /// </summary>
        public void Tick()
        {
            if (Time.time >= nextTime)
            {
                InstantiateMole();
                nextTime += _moleInstantiateInterval;
            } 
        }
        /// <summary>
        /// 清除一个Mole
        /// TODO: 对signal做出响应
        /// </summary>
        /// <param name="mole"></param>
        private void RemoveMole(Mole mole)
        {
            //注意，Unity中的GameObject具有唯一的Identfier，可以直接用来比较
            var targetMole = molePositionStates.FirstOrDefault(x =>x.Mole!=null && x.Mole.gameObject== mole.gameObject);
            if (targetMole is null)
            {
                return;
            }
            _molePool.Despawn(mole);
          
            var targetMolePositionState = molePositionStates[molePositionStates.ToList().IndexOf(targetMole)];
            if (targetMolePositionState !=null)
            {
                targetMole = null;
                targetMolePositionState.Mole = null;
            }
            
          
        }
        /// <summary>
        /// 实例化一个Mole
        /// </summary>
        private void InstantiateMole()
        {
            //首先选择Mole为null的位置
            var spareMolePositionState = molePositionStates.Where(x => x.Mole is null).ToArray();
            if (spareMolePositionState is null || spareMolePositionState.Length==0)
            {
                return;
            }
            //从筛选出来的数组中挑选一个随机值
            System.Random rnd = new System.Random();
            int randomIndex = rnd.Next(spareMolePositionState.Length); 
            MolePositionState selectedState = spareMolePositionState[randomIndex];
            //使用pool产生一个Mole
            selectedState.Mole = _molePool.Spawn(UnityEngine.Random.Range(1, 10) > 7 ? MoleTypes.Bad : MoleTypes.Good, selectedState.Position);
            selectedState.Mole.transform.position = selectedState.Position;
            Debug.Log(selectedState.Mole.transform.position);
        }

        /// <summary>
        /// 初始化MolePosition数组，
        /// 以plan左下角为起点，记为x=0,z=0
        /// ---------------
        /// 0,2     1,2     2,2       
        /// 0,1     1,1     2,1
        /// 0,0     1,0     2,0
        /// ---------------
        /// plane的大小为10*1.2=12，位置在Vector3.zero，Mole的位置应该为
        /// ---------------
        /// -4,4    0,4     4,4
        /// -4,0    0,0     4,0
        /// -4,-4   0,-4    4,-4
        /// ---------------
        /// </summary>
        private void SetInitMolePositionStates()
        {
            molePositionStates = new MolePositionState[9]
            {
                new MolePositionState(new Vector3(-4, -1, -4)),
                new MolePositionState(new Vector3(0, -1, -4)),
                new MolePositionState(new Vector3(4,  -1, -4)),
                new MolePositionState(new Vector3(-4,  -1, 0)),
                new MolePositionState(new Vector3(0 ,  -1, 0)),
                new MolePositionState(new Vector3(4,  -1, 0)),
                new MolePositionState(new Vector3(-4,  -1, 4)),
                new MolePositionState(new Vector3(0,  -1, 4)),
                new MolePositionState(new Vector3(4, -1, 4))
            };

        }
        /// <summary>
        /// Mole数据管理类
        /// </summary>
        private class MolePositionState
        { 
            /// <summary>
            /// Mole的位置
            /// </summary>
            public Vector3 Position { get; set; }
            /// <summary>
            /// 是否有Mole，若为空则无Mole，说明这个位置可以生成
            /// </summary>
            public Mole Mole { get; set; }

            public MolePositionState(Vector3 position)
            { 
                Position = position;
            }
        }
    }
}

